import jwt from "jsonwebtoken"

export function signJWT(payload) {
  const config = useRuntimeConfig()
  return jwt.sign(payload, config.jwtSecret, { expiresIn: "7d" })
}

export function verifyJWT(token) {
  try {
    const config = useRuntimeConfig()
    return jwt.verify(token, config.jwtSecret)
  } catch (error) {
    return null
  }
}

export function generateRefreshToken(userId) {
  const config = useRuntimeConfig()
  return jwt.sign({ userId }, config.jwtRefreshSecret, { expiresIn: "30d" })
}

export function verifyRefreshToken(token) {
  try {
    const config = useRuntimeConfig()
    return jwt.verify(token, config.jwtRefreshSecret)
  } catch (error) {
    return null
  }
}
/**
 * 生成Jwt token 并保存到cookie
 * @param {*} event 
 * @param {*} user 
 */
export function saveToken (event, user, rememberMe = false) {
  const token = signJWT({ 
    id: user.id, 
    email: user.email,
    name: user.name
   })

  setCookie(event, "auth-token", token, {
    httpOnly: true,
    secure: true,
    sameSite: "strict",
    maxAge: rememberMe ? 60 * 60 * 24 * 30 : 60 * 60 * 24
  })
} 
